<?php

namespace App\Imports;


use App\Models\AgentModel;
use App\Models\DictionaryModel;
use App\Models\dispatch\DriverModel;
use App\Models\OrderModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use stdClass;
use App\Models\DeptModel;
use App\Models\AdminRoleModel;

class CargoImport implements ToCollection, WithMultipleSheets
{


    private $result;

    public function __construct() {
        $this->result = new stdClass;
    }

    public function collection(Collection $rows){
        $lines = [];
        $this->result->error = [];



        foreach ($rows as $k => $row) {
            if($k < 1) continue;

            $sn = $row[0];
            $big_pkgs = $row[1];
            $pre_weight = $row[2];
            $destination = $row[3];
            $take_order_sn = $row[4];

            $find_order = OrderModel::query();
            if($sn){
                $find_order->where('sn', 'like', '%'.$sn.'%');
            }
            if($big_pkgs){
                $find_order->where('big_pkgs', $big_pkgs);
            }
            if($pre_weight){
                $find_order->where('pre_weight', $pre_weight);
            }
            if($destination){
                $find_order->where('destination', $destination);
            }
            $find_order = $find_order->first();
            if($find_order){
                if($find_order->cargo_status > 1){
                    $this->result->error[] = '第'.($k+1).'行：入仓单已配舱';
                }else{
                    $lines[] = [
                        'order_id' => $find_order->id,
                        'take_order_sn' => $take_order_sn,
                    ];
                }
            }else{
                $this->result->error[] = '第'.($k+1).'行：未匹配到对应入仓单';
            }
        }

        $this->result->lines = $lines;
    }

    public function sheets(): array {
        return [ 0 => $this];
    }

    public function get_result(){
        return $this->result;
    }


}
